<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card">
        <el-form ref="queryForm" :model="queryParams" :inline="true">
<!--          <el-form-item label="状态" prop="status">-->
<!--            <el-select v-model="queryParams.status" placeholder="状态" clearable size="small">-->
<!--              <el-option-->
<!--                v-for="dict in statusOptions"-->
<!--                :key="dict.value"-->
<!--                :label="dict.label"-->
<!--                :value="dict.value"-->
<!--              />-->
<!--            </el-select>-->
<!--          </el-form-item>-->

<!--          <el-form-item label="上传时间">-->
<!--            <el-date-picker-->
<!--              v-model="dateRange"-->
<!--              size="small"-->
<!--              type="datetimerange"-->
<!--              range-separator="至"-->
<!--              start-placeholder="开始日期"-->
<!--              end-placeholder="结束日期"-->
<!--              align="right"-->
<!--              value-format="yyyy-MM-dd HH:mm:ss"-->
<!--            />-->
<!--          </el-form-item>-->

<!--          <el-form-item label="课程关键字" prop="name">-->
<!--            <el-input-->
<!--              v-model="queryParams.name"-->
<!--              placeholder="请输入课程关键字"-->
<!--              clearable-->
<!--              size="small"-->
<!--              style="width: 160px"-->
<!--              @keyup.enter.native="handleQuery"-->
<!--            />-->
<!--          </el-form-item>-->
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb10" style="float:right">
          <el-col :span="1.5">
<!--            <router-link :to="{name:'AddNetworkCourse'}">-->
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="open_fun">
                <span>新增</span>
              </el-button>
<!--            </router-link>-->
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
            >删除</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button
              v-permisaction="['admin:sysConfig:export']"
              type="warning"
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
            >导出</el-button>
          </el-col>-->
        </el-row>

        <el-table
          v-loading="loading"
          :data="courseList"
          border
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChang"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" sortable="custom" width="75" type="index" />
          <!--          <el-table-column label="科目" prop="subject" :show-overflow-tooltip="true" />-->
          <el-table-column label="名称" prop="goods_title" :show-overflow-tooltip="true" />
          <el-table-column label="封面" prop="" width="60">
            <template slot-scope="scope">
              <!--              <el-image :src="getMediaUrl(scope.row.cover)" />-->
              <el-image :src="scope.row.goods_thumb" />
            </template>
          </el-table-column>
          <el-table-column
            label="状态"
            prop="status">
            <template slot-scope="scope">
              <span>{{ scope.row.status == -1?'关闭':'开启' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="价格" prop="charge" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ parseFloat(scope.row.charge)/100 }}</span>
            </template>
          </el-table-column>
          <!--          <el-table-column label="销量" prop="sales" :show-overflow-tooltip="true" />-->
          <!--          <el-table-column label="上传人" prop="creator" :show-overflow-tooltip="true" />-->
          <el-table-column label="创建时间" sortable="custom" prop="createdAt" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createdAt) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" class-name="small-padding fixed-width" width="160">
            <template slot-scope="scope">
              <el-row :gutter="10">
                <el-col :span="1.5">
                  <el-button @click="edit_fun(scope.row)" size="mini" type="text" icon="el-icon-edit">修改</el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                  >删除</el-button>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageIndex"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
        <!-- 添加或修改对话框 -->
        <el-drawer
          ref="drawer"
          :title="title"
          :visible.sync="open"
          direction="rtl"
          size="60%"
          custom-class="demo-drawer"
        >
          <div class="demo-drawer__content">
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
              <el-form-item label="团购名称" prop="goods_title">
                <el-input v-model="form.goods_title" placeholder="请输入团购名称" />
              </el-form-item>
              <el-form-item label="团购价格" prop="charge">
                <el-input v-model="form.charge" placeholder="请输入团购价格" />
              </el-form-item>
              <el-form-item label="拼团人数" prop="people_num">
                <el-input v-model="form.people_num" placeholder="请输入拼团人数" />
              </el-form-item>
              <el-form-item label="开始时间" prop="started_at">
                <el-date-picker
                  v-model="form.started_at"
                  type="datetime"
                  placeholder="开始时间"
                />
              </el-form-item>
              <el-form-item label="结束时间" prop="ended_at">
                <el-date-picker
                  v-model="form.ended_at"
                  type="datetime"
                  placeholder="结束时间"
                />
              </el-form-item>
              <el-form-item label="团购封面" prop="goods_thumb">
                <el-upload
                  :headers="headers"
                  :action="$uploadUrl"
                  list-type="picture-card"
                  :show-file-list="false"
                  :before-upload="beforeUpload"
                  :on-success="uploadSuccess"
                  :on-remove="handleRemove"
                >
                  <el-image v-if="form.goods_thumb" :src="form.goods_thumb" class="upload-image" />
                  <i v-else class="el-icon-plus" />
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
                </el-upload>
              </el-form-item>
              <el-form-item label="状态" prop="status">
                <el-switch
                  v-model="form.status"
                  style="width: 40%"
                  :active-value="1"
                  :inactive-value="-1"
                  active-text="开启"
                  inactive-text="关闭"
                />
              </el-form-item>
              <el-form-item label="机器人参团" prop="robot_join" style="white-space: nowrap">
                <el-switch
                  v-model="form.robot_join"
                  style="width: 40%"
                  :active-value="1"
                  :inactive-value="-1"
                  active-text="是"
                  inactive-text="否"
                />
              </el-form-item>
              <el-form-item label="商品类型" prop="province">
                <el-select
                  v-model="form.goods_type"
                  filterable
                  placeholder="请选择商品类型"
                  style="width: 100%"
                  @change="goodsTypeFun"
                >
                  <el-option
                    v-for="(item, index) in goodsTypeList"
                    :key="index"
                    :label="item.name"
                    :value="item.val"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="选择商品" prop="goods_id">
                <el-select
                  v-model="form.goods_id"
                  filterable
                  remote
                  placeholder="请选择商品"
                  style="width: 100%"
                  :remote-method="remoteMethod"
                  :loading="selectload"
                  @change="change_goods_charge"
                >
                  <el-option
                    v-for="(item, index) in goodsList"
                    :key="index"
                    :label="item.name"
                    :value="item.course_id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="商品原价" prop="goods_charge" >
                <el-input v-model="form.goods_charge" disabled placeholder="请输入商品原价" />
              </el-form-item>
<!--              <el-form-item label="文章内容" prop="academy_content" class="consultContent">-->
<!--                <Ckeditor v-model="form.academy_content" :content="form.academy_content" />-->
<!--              </el-form-item>-->
            </el-form>
            <div class="demo-drawer__footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </div>
        </el-drawer>
      </el-card>
    </template>
  </BasicLayout>
</template>

<script>
// import { listCourse, delCourse } from '@/api/admin/sys-course'
import * as api from '@/api/admin/sys-course'
import { formatJson } from '@/utils'
import { getToken } from '@/utils/auth'
export default {
  name: 'SysConfigManage',
  data() {
    return {
      selectload: false,
      goodsTypeList:[
        {
          name:'线上课程',
          val:'online'
        },
        {
          name:'直播课程',
          val:'live'
        },
        {
          name:'套餐课程',
          val:'combo'
        }
      ],
      open:false,
      title:'新增团购',
      // 遮罩层
      loading: true,
      // 选中数组
      courseIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 表格数据
      courseList: [],
      // 排序字段
      order: 'createdAtOrder',
      // 弹出层标题
      title: '',
      isEdit: false,
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        status: undefined,
        created_at: undefined,
        name: undefined,
        course_type: 'online'
      },
      host: '',
      statusOptions: [
        { label: '上架', value: 1 },
        { label: '下架', value: -1 }
      ],
      form:{},
       // 表单校验
      rules: {
        goods_title: [
          { required: true, message: '团购名称不能为空', trigger: 'blur' }
        ],
        charge: [
          { required: true, message: '价格不能为空', trigger: 'blur' }
        ],
        // wz_url: [{ required: true, message: '请上传封面图片' }],
        // academy_introduction: [
        //   { required: true, message: '请输入描述', trigger: 'blur' }
        // ],
        // province: [{ required: true, message: '请选择地区', trigger: 'blur' }],
        // academy_content: [
        //   { required: true, message: '请输入内容', trigger: 'blur' }
        // ]
      },
      headers: { Authorization: 'Bearer ' + getToken() },
      goodsList:[]
    }
  },
  created() {
    this.getList()
    this.host = process.env.VUE_APP_BASE_API
  },
  methods: {
    change_goods_charge(e){ // 改变商品原价
      var new_data = this.goodsList.filter(item => {
        return item.course_id == e
      })
      this.form.goods_charge = parseFloat(new_data[0].price)/100
    },
    async getGoodsIInfo(goods_type = '', name = ''){ // 获取课程信息
      var func_name = ''
      if(!goods_type){
        goods_type = this.goodsTypeList[0].val
      }
      switch(goods_type) {
        case this.goodsTypeList[0].val: // 线上课程
          func_name = 'listCourse'
          break;
        case this.goodsTypeList[1].val: // 直播课程
          func_name = 'listCourseLive'
          break;
        case this.goodsTypeList[2].val: // 套餐课程
          func_name = 'offlineCourse'
          break;
      }
      const params = {
        pageIndex:1,
        pageSize:100,
      }
      if(name){
        params.name = name
      }
      const res = await api[func_name](params)
      if(res.code == 200) {
        this.goodsList = res.data.list
        // console.log(this.goodsList)
        this.selectload = false
      }
    },
    async getGoodsIDetail(goods_type = '', id = ''){ // 获取课程信息 详情
      var func_name = ''
      if(!goods_type){
        goods_type = this.goodsTypeList[0].val
      }
      switch(goods_type) {
        case this.goodsTypeList[0].val: // 线上课程
          func_name = 'getDetails'
          break;
        case this.goodsTypeList[1].val: // 直播课程
          func_name = 'getLiveCourse'
          break;
        case this.goodsTypeList[2].val: // 套餐课程
          func_name = 'getOfflineDetails'
          break;
      }
      const res = await api[func_name](id)
      if(res.code == 200) {
         var name = ''
        if(goods_type == this.goodsTypeList[0].val) {
          name = res.data.step1.name
        }
        else if(goods_type == this.goodsTypeList[2].val) {
          name = res.data.Combo_step1.name
        }
        else{
          name = res.data.name
        }
        console.log(name)
        this.getGoodsIInfo(goods_type,name)
      }
    },
    goodsTypeFun(e){ // 切换商品类型
      // console.log(e)
      this.form.goods_id = ''
      this.getGoodsIInfo(e)
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(async valid => {
        if (valid) {
          if (this.form.id) { // 编辑
            const params = this.form
            params.charge = parseFloat(parseFloat(params.charge)*100)
            params.goods_charge = parseFloat(parseFloat(params.goods_charge)*100)
            params.people_num = parseInt(params.people_num)
            // console.log(params); return
            const res = await api.editGroupPurchase(params)
            if(res.code == 200) {
              this.$message({
                message: '编辑成功',
                type: 'success'
              });
              this.open = false;
              this.getList()
            }
            else{
              this.$message.error('编辑失败');
            }
          }
          else{ // 新增
            const params = this.form
            params.charge = parseFloat(parseFloat(params.charge)*100)
            params.goods_charge = parseFloat(parseFloat(params.goods_charge)*100)
            params.people_num = parseInt(params.people_num)
            // console.log(params); return
            const res = await api.addGroupPurchase(params)
            if(res.code == 200) {
              this.$message({
                message: '添加成功',
                type: 'success'
              });
              this.open = false;
              this.getList()
            }
            else{
              this.$message.error('添加失败');
            }
          }
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    handleRemove() {
      this.form.wz_url = ''
    },
    uploadSuccess(res, file) {
      this.form = {
        ...this.form,
        goods_thumb: res.data.full_path
      }
    },
    beforeUpload(file) {
      const isLt05M = file.size / 1024 / 1024 < 2
      const isJPG = file.type.indexOf('image/') === -1
      if (isJPG) {
        this.$message.error(
          '文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件'
        )
      }
      if (!isLt05M) {
        this.$message.error('上传头像图片大小不能超过 2M!')
      }
      return !isJPG && isLt05M
    },
    remoteMethod(query) {
      // console.log(query)
      if (query !== '') {
        this.selectload = true
        this.getGoodsIInfo(this.form.goods_type || '',query)
        // getCity({ name: query }).then(res => {
        //   this.cityList = res?.data || []
        //   this.selectload = false
        // })

      } else {
        this.goodsList = []
      }
    },
    // 编辑
    edit_fun(row) {
      this.form = row
      this.form.charge = parseFloat(this.form.charge)/100
      this.form.goods_charge = parseFloat(this.form.goods_charge)/100
      // form.goods_charge
      this.open = true;
      this.title = '修改团购信息'
      this.getGoodsIDetail(this.form.goods_type,this.form.goods_id)
    },
    open_fun() { // 新增
      this.form = {}
      this.open = true;
      this.form.goods_type = this.goodsTypeList[0].val
      this.title = '添加团购信息'
      this.getGoodsIInfo()
    },
    /** 查询参数列表 */
    async getList() {
      this.loading = true
      const res = await api.groupPurchaseList(this.queryParams)
      // console.log(res)
      if (res.code == 200) {
        // res.data.list.map((item,i) => {
        //   item.charge = parseFloat(item.charge)/100
        // })
        this.courseList = res.data.list
        this.total = res.data.count
        this.loading = false
      }
    },
    // 参数系统内置字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageIndex = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleSortChang(column, prop, order) {
      prop = column.prop
      order = column.order
      if (this.order !== '' && this.order !== prop + 'Order') {
        this.queryParams[this.order] = undefined
      }
      if (order === 'descending') {
        this.queryParams[prop + 'Order'] = 'desc'
        this.order = prop + 'Order'
      } else if (order === 'ascending') {
        this.queryParams[prop + 'Order'] = 'asc'
        this.order = prop + 'Order'
      } else {
        this.queryParams[prop + 'Order'] = undefined
      }
      this.getList()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.courseIds = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = (row.id && [row.id]) || this.courseIds
      this.$confirm('是否确认删除', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          return api.delGroupPurchase({ ids })
        })
        .then(response => {
          if (response.code === 200) {
            this.msgSuccess(response.msg)
            this.getList()
          } else {
            this.msgError(response.msg)
          }
        })
        .catch(function() {})
    },
    /** 导出按钮操作 */
    handleExport() {
      // const queryParams = this.queryParams
      this.$confirm('是否确认导出所有参数数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = [
            '参数主键',
            '参数名称',
            '参数键名',
            '参数键值',
            '备注',
            '创建时间'
          ]
          const filterVal = [
            'configId',
            'configName',
            'configKey',
            'configValue',
            'remark',
            'createdAt'
          ]
          const list = this.configList
          const data = formatJson(filterVal, list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: '参数设置',
            autoWidth: true, // Optional
            bookType: 'xlsx' // Optional
          })
          this.downloadLoading = false
        })
      })
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
